//
//  UserConfigViewController.m
//  MapLink
//
//  Created by student on 5/19/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "UserConfigViewController.h"
#import "GroupListViewController.h"
#import "AppConfig.h"
#import "JSON/JSON.h"
#import "NetworkManager.h"
#import "UIImage-Extensions.h"

#import "OCPromptView.h"  // AlertViewWithTextbox

@implementation UserConfigViewController
@synthesize delegate, imgView, buffer, displayName, deviceID;

-(id) init {
//	return [super initWithNibName:@"UserConfigViewController" bundle:nil];

	// meng
	return [super initWithNibName:@"UserConfigViewController" bundle:nil];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
	return [self init];
}

-(id) initWithAppConfig:(AppConfig *) object withDeviceID:(NSString *)string {
	self = [self init];
	appConfig = object;
	deviceID = string;
	return self;
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	
	//textDisplayName.text = displayName;
	NSLog(@"viewWillAppear");
	saveButton.enabled = YES;
	labelStatus.text = @"";
	
	NSString * photopath=[[AppConfig getDocumentFolder] stringByAppendingPathComponent:[appConfig getProperty:@"user-avatar"]];
	NSLog(@"Load image: %@", photopath);
	UIImage *img = [UIImage imageWithContentsOfFile:photopath];
	
	imgView.image = img;
}

/* START: Connection delegate */
-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *) response {
	[buffer setLength:0];
}
-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) data {
	[buffer appendData:data];
}
-(void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error {
	[buffer release];
	[connection release];
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection {
	NSLog(@"Done with bytes %d", [buffer length]);
	
	NSMutableString *jsonString = [[NSMutableString alloc] initWithBytes:[buffer mutableBytes]
																  length:[buffer length]
																encoding:NSUTF8StringEncoding];
	NSDictionary *response = [jsonString JSONValue];
	NSString *result = [response objectForKey:@"result"];
	NSString *error = [response objectForKey:@"message"];
	
	saveButton.enabled = NO;
	[activityIndicatorView stopAnimating];
	
	if ([result isEqualToString:@"Y"]) {
		// Successful
		[self dismissModalViewControllerAnimated:YES];
	} else {
		// Error
		NSLog(@"ERROR: %@", error);
	}
	
	[jsonString release];
	
	[connection release];
}
/* END: Connection delegate */

-(IBAction)save {
	NSLog(@"UserConfigViewController: save user configuration");
	[activityIndicatorView startAnimating];
	
	[appConfig setProperty:@"user-name" setValueTo:textDisplayName.text];
	[appConfig setProperty:@"user-auth-code" setValueTo:textAuthCode.text];
	[appConfig setProperty:@"user-avatar" setValueTo:@"avatar.png"];

	[textDisplayName resignFirstResponder];

	if ([NetworkManager connectedToNetwork] && (changed)) {
		labelStatus.text = @"Trying to upload photo to server...";
		saveButton.enabled = NO;
		
		NSString *filename = [NSString stringWithFormat:@"%@.png",textDisplayName.text];
		NSData *imageData = UIImagePNGRepresentation(imgView.image);
		// setting up the URL to post to
		NSString *urlString = [NSString stringWithFormat:@"http://mybuddies.emiu.net/upload.php?device_id=%@",deviceID];
		
		// setting up the request object now
		NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
		[request setURL:[NSURL URLWithString:urlString]];
		[request setHTTPMethod:@"POST"];
		
		NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
		NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
		[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
		
		/*
		 now lets create the body of the post
		 */
		NSMutableData *body = [NSMutableData data];
		[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
		[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"fileupload\"; filename=\"%@\"\r\n",filename] dataUsingEncoding:NSUTF8StringEncoding]];
		[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
		[body appendData:[NSData dataWithData:imageData]];
		[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
		// setting the body of the post to the reqeust
		[request setHTTPBody:body];
		
		// now lets make the connection to the web
		conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
		if (conn) {
			self.buffer = [NSMutableData data]; 
		}
	} else {
		if (![NetworkManager connectedToNetwork]) {
			labelStatus.text = @"ERROR: Network is not available.";
		}
		[activityIndicatorView stopAnimating];
		[self dismissModalViewControllerAnimated:YES];
	}
}

-(IBAction)cancel {
	NSLog(@"UserConfigViewController: cancel");
	[self dismissModalViewControllerAnimated:YES];
}





// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	NSLog(@"viewDidLoad");
	
	textDisplayName.text = [appConfig getProperty:@"user-name"];
	textAuthCode.text = [appConfig getProperty:@"user-auth-code"];
	changed = NO;
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[delegate release];
	[imgView release];
	[deviceID release];
	[buffer release];
	[displayName release];
    [super dealloc];
}


// UIImagePickerControllerDelegate methods ----------------------------------


// meng code
-(IBAction) pickImage: (id) sender {
	cameraUsed = NO;
	
	UIImagePickerController *ipicker = [[UIImagePickerController alloc] init];
	//if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] ) {
	//	ipicker.sourceType = UIImagePickerControllerSourceTypeCamera;
	//}
	//else {
		ipicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
	//}
		
	ipicker.delegate = self;

	ipicker.allowsEditing = NO;
	[self presentModalViewController:ipicker animated:YES];

	
}

-(IBAction) takePhoto: (id) sender {
	cameraUsed = YES;
	UIImagePickerController *ipicker = [[UIImagePickerController alloc] init];
	if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] ) {
		ipicker.sourceType = UIImagePickerControllerSourceTypeCamera;
	}
	else {
		[ipicker release];
		UIAlertView *alertView = [[UIAlertView alloc] 
								  initWithTitle:@"Error" 
								  message:@"Camera is not available on your device" 
								  delegate:nil 
								  cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alertView show];
		[alertView release];
		
		return;
	}
	
	ipicker.delegate = self;
	
	ipicker.allowsEditing = NO;
	[self presentModalViewController:ipicker animated:YES];
}

- (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    
    UIGraphicsEndImageContext();
    return newImage;
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
	NSLog(@"Image picked");
	changed = NO;
	
	NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
	
    if ([mediaType isEqualToString:@"public.image"]){
		NSData *imageData = UIImagePNGRepresentation([info objectForKey:UIImagePickerControllerOriginalImage]);
		UIImage *originalImage;
		if (cameraUsed) {
			originalImage = [[UIImage imageWithData:imageData] imageRotatedByDegrees:90.0];
		} else {
			originalImage = [UIImage imageWithData:imageData];
		}

		UIImage *selectedImage = [self imageWithImage:originalImage scaledToSize:CGSizeMake(148.0f,180.0f)];
		
		if (selectedImage) {
			NSString * photopath=[[AppConfig getDocumentFolder] stringByAppendingPathComponent:[appConfig getProperty:@"user-avatar"]];
			NSLog(@"Trying to write photo to: %@", photopath);
			[UIImagePNGRepresentation(selectedImage) writeToFile:photopath atomically:YES];
			changed = YES;
		}
    }
	
	[self dismissModalViewControllerAnimated:YES];
	[picker release];
}

-(void) imagePickerControllerDidCancel:(UIImagePickerController *)picker {
	changed = NO;
	[self dismissModalViewControllerAnimated:YES];
	[picker release];
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo; 
{
	if (!error) {
		//showAlert(@"Image written to photo album");
		NSLog(@"image was saved");
	}
	else {
		// showAlert(@"Error writing to photo album: %@", [error localizedDescription]);
		NSLog(@"error saving image to photo album: %@", [error localizedDescription]);
	}
}

// UITextFieldDelegate ----------------

-(BOOL) textFieldShouldReturn:(UITextField *)textField {
	// [self save];
	if (textField.tag == 99 ) {
		NSLog(@"textfield tag is %d", textField.tag);	
		[self performSelector:@selector(promptAuthenticationReEnter) withObject:nil afterDelay: 0.3];

	}
	
	[textField resignFirstResponder];
	return YES;
}


- (void) promptAuthenticationReEnter {
	input = [[OCPromptView alloc] initWithPrompt:@"Re-enter auth code:" delegate:self cancelButtonTitle:nil acceptButtonTitle:@"OK"];
	[input show];
	[input autorelease];

}

- (void) informMismatchAuthentication {
	msg = [[UIAlertView alloc] initWithTitle:@"Message" message:@"Mismatched authentication code entered" delegate:self cancelButtonTitle:nil otherButtonTitles:nil	];
	[msg show];
	[msg resignFirstResponder];


	
	[self performSelector:@selector(dismissAlert) withObject:nil afterDelay:5.0];

	
	
}

- (void) dismissAlert {
	[msg dismissWithClickedButtonIndex:0 animated:NO];
	[msg autorelease];
	
}

// UIAlertViewDelegate ---------------

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
	if (buttonIndex != [alertView cancelButtonIndex]) {
		NSString* resp = [(OCPromptView *)alertView enteredText];

		NSLog(@"Entered text is %@", resp );
		if (![resp isEqualToString:textAuthCode.text ])
			[self performSelector:@selector(informMismatchAuthentication) withObject:nil afterDelay: 0.5];

	}
}


@end
